clear
set more off
set type double,perm



// Notes
// Reflection specificaitons after Jan week 1 meeting
// requires estaddfirst to be run first
//
// Jan 15th.
// March 16th
// Sept 2023


// data
use ${wd}/reg_union_${ind}_${area}_`2'_case_`3'.dta, clear

gen temp = 0 if union == 1
replace temp = 1 if union == 0
replace union = temp

drop temp


// reshape for non-union wages
reshape wide reswage union_density sample_ic reg_wgt prem union_premium n_* pn*  E_* RTW N_to_U  , i( year $ind ${area} ) j(union) 
renvars *0, postdrop(1)
renvars E_c1 E_c E_1c1 E_0c1 E_hat_n1 E_tilde_n1 E_hat_u1 E_tilde_u1 E_hat1 E_tilde1, postsub(1 u) 


// Instruments
	gen IV    = E_hat - E_tilde
	gen IV_n  = E_hat_n - E_tilde_n
	gen IV_u  = E_hat_u - E_tilde_u
	
// Bring in Union Proportion
	merge 1:1 ${ind} ${area} year2 using  ${wd}/keyvars/propic.dta
	drop if _merge==2
	drop _merge

// Bring in ER data
	merge m:1 ${area} year2 using  ${wd}/keyvars/emp.dta
	drop if _merge==2
	drop _merge	

// new at city-ind
	merge 1:1 ${ind} ${area} year2 using  ${wd}/keyvars/union_elections_${area}_${ind}.dta
	drop _merge

// unit x time
	egen ic = group($area $ind) 
	tsset ic (year), yearly
	tsset


// Sample and changes
keep if sample_ic > 10 


	
// In changes
	tsset
		foreach var of varlist  E_*    cert* { //poDE pER*  UoE* cert*
			gen d`var' = D.`var'
		}	
	
gen dwage = D.reswage
gen dpropic = D.propic
gen dER     = D.lnEP_c
gen dER2 = exp(lnEP_c) - exp(L.lnEP_c)

// Weights
//*********************************************************
bysort ic (year): gen weight = 1/(1/sqrt(sample_ic)+1/sqrt(sample_ic[_n-1]))
egen sw = sum(weight), by(year2)
replace weight = weight/sw
drop sw

// Keep Industries that observed more than once each year
bys ${ind} year2: g num=_N
keep if num>1
drop num

// Controls and Cluster
//*********************************************************
egen controls=group(year2 ${ind})
egen clusters=group(year2 ${area})

// Labels
//**********************************************************

// Outside Option terms
lab var dE_c  "$ \Delta E_{ucit} $"
label var dER "$\Delta ER_c$"
lab var dpropic "$ \Delta P_{ic} $"


save ${wd}/reg_dataRRv3_Union_${ind}_${area}_`2'_case_`3'.dta, replace
